#include <stdio.h>
#include <stdlib.h>
#include "log.h"
#include "cJSON.h"

#define STR_TO_CJSON 0

char *datas = "{\"name\":\"Su_da\",\"age\":23,\"career\":\"student\",\"wage\":10000}";
int main(int argc, char const *argv[])
{
#if (STR_TO_CJSON == 1)
    {
        // 创建 json对象
        cJSON *json = cJSON_CreateObject();
        if (json == NULL)
        {
            log_info("josn对象创建失败\n");
            return -1;
        }
        // 添加 键值到json对象
        cJSON_AddStringToObject(json, "name", "Su_da");
        cJSON_AddNumberToObject(json, "age", 23);
        cJSON_AddStringToObject(json, "career", "student");
        cJSON_AddNumberToObject(json, "wage", 10000);
        // 将json对象转化为字符串
        char *str = cJSON_PrintUnformatted(json);
        if (str == NULL)
        {
            log_info("str 为空\n");
        }
        log_info("json非标准格式:\n %s\n", str);
        log_info("=======================\n");
        // 释放json字符串内存
        free(str);
        // 释放json对象内存
        cJSON_Delete(json);
    }
#else
    {
        //解析字符串 爲json對象
        cJSON* json = cJSON_Parse(datas);
        if(json == NULL)
        {
            log_info("josn对象创建失败\n");
            return -1;
        }

        //提取JSON中字符段对应值
        cJSON* name = cJSON_GetObjectItemCaseSensitive(json,"name");
        cJSON* age = cJSON_GetObjectItemCaseSensitive(json,"age");
        cJSON* career = cJSON_GetObjectItemCaseSensitive(json,"career");
        cJSON* wage = cJSON_GetObjectItemCaseSensitive(json,"wage");

        log_info("name: %s\n",name->valuestring);
        log_info("age: %d\n",age->valueint);
        log_info("career: %s\n",career->valuestring);
        log_info("wage: %d\n",wage->valueint);

        //只需要释放 根json对象即可 不需要去释放子json对象
        cJSON_Delete(json);
    }
#endif
    return 0;
}
